const request = require('superagent')
const cheerio = require('cheerio')
const { weather_url } = require("../config/index.js")
const { changeToArray } = require("../utils/index.js")
/** 天气-墨迹天气爬取版 */
const types = {
  tod: 'today',
  tom: 'tommorrow',
  tdat: 'tdat'
}

async function getFutureWeather (type = types.tom) {
  return new Promise((resolve) => {
    request.get(weather_url(type)).then(res => {
      let $ = cheerio.load(res.text)
      let weatherMsg = {
        date: $('#detail_info .detail_time').text().replace(/[\r\n]/g, ' ').trim(),
        district: $('#search .search_default').text().replace(/[\r\n]/g, ' ').trim().split('， '),
        state_now: changeToArray($('#detail_info .detail_weather').text())
      }
      resolve(weatherMsg)
      console.log('天气：', weatherMsg, '\n', weatherMsg.district[1], weatherMsg.district[0])
    })
  })
}

async function getTodayWeather () {
  return new Promise(resolve => {
    request.get(weather_url(types.tod)).then(res => {
      let $ = cheerio.load(res.text)
      let weatherMsg = {
        p1: changeToArray($('.detail_wea .now').text().replace(/[\r\n]/g, ' ').trim()),
        p2: changeToArray($('.detail_wea .day').eq(0).text().replace(/[\r\n]/g, ' ').trim()),
        p3: changeToArray($('.detail_wea .day').eq(1).text().replace(/[\r\n]/g, ' ').trim())
      }
      resolve(weatherMsg)
      console.log('tt', weatherMsg)
    })
  })
}

/** 天气-和风天气接口版 */
async function getNowHeFeng () {
  request.get('https://free-api.heweather.net/s6/weather/forecast?location=minhang&key=7933d45f77884ddbaff2b162d35396ae').then(res => {

    // console.log('tt', typeof res.body, res.body.HeWeather6)
    console.table(res.body.HeWeather6.daily_forecast)
  })
}
getNowHeFeng()
module.exports = {
  getFutureWeather,
  getTodayWeather
}